<template>
  <div style="position: absolute; height: 100%; width: 100%">
    <FormDesign v-model="fieldConfigs" />
  </div>
</template>
<script>
import FormDesign from "xqjr-plugin-form/FormDesign";
export default {
  name: "FormSet",
  components: { FormDesign },
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      val: null,
      source: [],
      id: this.$route.query.id,
      fieldConfigs: [],
      sourceData: []
    };
  },
  watch: {
    value(val) {
      this.buildForm();
    }
  },
  methods: {
    handleFormDesignSave() {
      this.sourceData = this.transJsonToSource(this.fieldConfigs);
      this.$emit("input", this.sourceData);
      this.$emit("change", this.sourceData);
    },
    buildForm() {
      this.fieldConfigs = this.value.map(v => {
        v.props.id = v.id;
        v.props.flowFormName = v.label;
        v.props.flowId = v.id;
        return v.props;
      });
    },
    transSourceToJson() {
      const list = [];
      this.sourceData.map(item => {
        if (!!item.props) {
          list.push(item.props);
        }
      });
    },
    transJsonToSource(list) {
      const newList = [];
      for (let i = 0; i < list.length; i++) {
        newList.push(this.buildItem(list[i], i));
      }
      return newList;
    },
    buildItem(item, idx) {
      return {
        flowId: this.id,
        code: item.model,
        id: item.id,
        print: false,
        label: item.wrapper.label,
        props: item,
        sort: idx,
        widgetType: item.type,
        required: this.isRequired(item.decorator.rules)
      };
    },
    isRequired(rules) {
      if (rules && rules.length) {
        for (let i = 0; i < rules.length; i++) {
          if (Object.keys(rules[i]).includes("required") && rules[i]["required"]) {
            return true;
          }
        }
      }
      return false;
    }
  }
};
</script>
